import { createRouter, createWebHashHistory } from 'vue-router'
import { ElMessage } from 'element-plus'


// 登录页和容器页
import LoginPage from "@/components/LoginPage"
import MainContainer from "@/components/MainContainer"

// 欢迎页
import WelcomeView from "@/views/WelcomeView"

// 用户管理
import UserManagement from "@/views/UserManagement"



// 院校信息
import CollegeInfo from "@/views/CollegeInfo"

// 专业信息
import MajorInfo from "@/views/MajorInfo"

// 视频学习
import VideoStudy from "@/views/VideoStudy"

// 学习计划
import StudyPlan from "@/views/StudyPlan"

// 咨询信息
import CounselingMessage from "@/views/CounselingMessage"

// 个人信息
import PersonalInfo from "@/views/PersonalInfo"


// 路由配置
const router = createRouter({
   history: createWebHashHistory(),
   routes: [
      {
         path: '/', // 根路径
         redirect: '/login' // 重定向到登录页面
      },
      {
         path: '/login',
         component: LoginPage
      },
      {
         path: "/index",
         component: MainContainer,
         children: [
            {
               name: "欢迎页",
               path: "",
               component: WelcomeView
            },
            {
               name: "用户管理",
               path: "/userManagement",
               component: UserManagement
            },
            {
               name: "院校信息",
               path: "/collegeInfo",
               component: CollegeInfo
            },
            {
               name: "专业信息",
               path: "/majorInfo",
               component: MajorInfo
            },
            {
               name: "视频学习",
               path: "/videoStudy",
               component: VideoStudy
            },
            {
               name: "学习计划",
               path: "/studyPlan",
               component: StudyPlan
            },
            {
               name: "咨询动态",
               path: "/counselingMessage",
               component: CounselingMessage
            },
            {
               name: "个人中心",
               path: "/personalInfo",
               component: PersonalInfo
            }
         ]
      }
   ]
})


router.beforeEach((to, from, next) => {

   // 如果未匹配到路由
   // 防止搜索栏乱输入其他没有的页面路径
   if (to.matched.length === 0) {
      return next(from.path);
   }

   // 登录校验优化，除登录页面外，进入其他页面需要验证localStorage中是否有token，没有则跳转登录页面
   // 此处可以避免切换页面时，请求发出到响应“用户未登录”的时间间隔内，页面不会先刷新出来
   // 同时，路由切换到一个不会发送请求的页面时，可以实现登录校验功能
   // 故登录校验一共有两处，一处在此，路由切换校验，但可能存在服务端token过期的情况
   // 第二处位于接口请求出，每次请求如果localStorage中有token，则设置请求头，让服务端进行登录校验
   if (to.path !== "/login" && !localStorage.getItem("token")) {
      ElMessage({
         type: "warning",
         message: "请先登录",
         duration: 2000
      });
      return next("/login");
   }

   return next();
})


export default router